// 管理 WebSocket 连接的模块
const webSocketModule = (function() {
	let ws = null;
	let location = {
		longitude: 119.2165512,
		latitude: 26.0426396
	};



	const connectWebSocket = async (userData) => {

		const query = {
			userTel: userData.userTel,
			location: JSON.stringify({
				longitude: 119.2165512,
				latitude: 26.0426396
			})
		};
		console.log("query: " + JSON.stringify(query));

		try {
			ws = await uniCloud.connectWebSocket({
				name: "web",
				query: query
			});

			setupWebSocketListeners();
			return ws;
		} catch (error) {
			console.error('WebSocket 连接错误:', error.message, error.stack);
			uni.showToast({
				title: '网络故障'
			});
			return null;
		}
	}

	function setupWebSocketListeners() {
		console.log("ws: " + JSON.stringify(ws));
		ws.onOpen((res) => {
			uni.showToast({
				title: '已连接',
				res
			});
		});
		ws.onClose(() => {
			console.log('连接关闭了');
		});
		ws.onError((error) => {
			if (error) {
				console.log('连接错了', error);
				if (error.code) {
					console.log('错误代码:', error.code);
				}
				if (error.reason) {
					console.log('错误原因:', error.reason);
				}
			} else {
				console.log('连接错了，但没有错误信息');
			}
		});
		ws.onMessage((msg) => {
			const formatmsg = JSON.parse(msg.data)

			if (formatmsg.type === "msg") {
				uni.$emit("msg", JSON.parse(msg.data))
			}





		});
	}

	function closeWebSocket() {
		if (ws) {
			ws.close();
			ws = null;
		}
	}

	const sendMsg = (msgType, Target, content, user) => {
		if (typeof content !== 'object' || content === null) {
			console.error('content 必须是一个对象');
			return null;
		}
		const senderLocation = location;
		let msgContent = {
			text: "",
			voicePath: "",
			duration: 0,
			sendGoodId: "",
			sendshopId: "",
			mediaPath: "",
			unsend: true,
			senderLocation: senderLocation
		};
		msgContent = {
			...msgContent,
			...content
		};
		const msg = {
			sendUserId: user?.userId,
			userTel: user?.userTel,
			nicPic: user?.nicPic,
			nicName: user?.nicName,
			content: msgContent,
			location: location,
			toTarget: Target,
			messageType: msgType,
			webSocketType: 'msg',
			push_clientid: "",
			timestamp: Date.now(),
			receiveDistance: 3000,
			isRequest: false
		};
		try {
			console.log(ws, location, user, senderLocation);
			if (ws && location && user && senderLocation) {


				ws.send({
					data: JSON.stringify(msg)
				});
				return msg;
			} else {
				console.error('无法发送消息，WebSocket 连接未打开或必要数据缺失' + JSON.stringify(error));
				return null;
			}
		} catch (e) {
			console.error('发送消息时出现错误:', e.message);
			uni.showToast({
				title: '消息发送失败'
			});
			return null;
		}
	}

	return {
		connectWebSocket,
		sendMsg,
		closeWebSocket
	};
})();

// 修改为默认导出
export default webSocketModule;